﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace Willow.Authorization
{
    public class OnlineContext
    {

        private readonly static Lazy<OnlineContext> _instance = new Lazy<OnlineContext>(() => new OnlineContext());
        private Dictionary<string, LoginUser> userList = new Dictionary<string, LoginUser>();
        private static readonly string ONLINE_ACCOUNT_SESSION_NAME = "OnlineAccount";
        public static OnlineContext Instance
        {
            get
            {
                return _instance.Value;
            }
        }
        private OnlineContext()
        {
        }

        /// <summary>
        /// 添加用户
        /// </summary>
        /// <param name="user">The user.</param>
        public void Add(LoginUser user)
        {
            var sessionID = HttpContext.Current.Session.SessionID;
            user.SessionID = sessionID;
            user.LoginTime = DateTime.Now;

            if (userList.ContainsKey(sessionID))
            {
                userList[sessionID] = user;
            }
            else
            {
                userList.Add(sessionID, user);
            }
            HttpContext.Current.Session.Add(ONLINE_ACCOUNT_SESSION_NAME, user);
        }
        /// <summary>
        /// 获取当前用户
        /// </summary>
        /// <returns></returns>
        public LoginUser GetCurrentUser()
        {
            var sessionId = HttpContext.Current.Session.SessionID;
            LoginUser user = null;
            userList.TryGetValue(sessionId, out user);
            return user;
            //return HttpContext.Current.Session[ONLINE_ACCOUNT_SESSION_NAME] as LoginUser;
        }

        public IEnumerable<LoginUser> GetAllUser()
        {
            return userList.Values.Select(p => p);
        }

        public void RemoveUser(string sessionID)
        {
            userList.Remove(sessionID);
        }

        /// <summary>
        /// 注销用户
        /// </summary>
        public void Logout()
        {
            var sessionId = HttpContext.Current.Session.SessionID;
            userList.Remove(sessionId);
            HttpContext.Current.Session.Remove(ONLINE_ACCOUNT_SESSION_NAME);
        }

    }
}
